package com.hayukleung.voiceserver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.hayukleung.util.Constants;

public class Pool extends Thread
{
  public String id;
  public String message;
  public Set<String> ipSet = new HashSet<String>();

  public synchronized void remove(String ip)
  {
    ipSet.remove(ip);
  }

  public Pool()
  {
  	// one voice message one pool
    id = new Date().getTime() + "";
    // debug
    /*
    ipSet.add("192.168.137.11");
    ipSet.add("192.168.137.12");
    ipSet.add("192.168.137.13");
    ipSet.add("192.168.137.14");
    ipSet.add("192.168.31.11");
    ipSet.add("192.168.31.12");
    ipSet.add("192.168.31.13");
    ipSet.add("192.168.31.14");
    */
  }

  public boolean isPoolEnd = false;

  @Override
  public void run()
  {
    super.run();

    try
    {
      System.out.println("broadcast message ...");
      DatagramSocket datagramSocket = new DatagramSocket();
      for (int i = 0; i < Constants.REPEAT_TIME; i++)
      {
        System.out.println("====== " + i + " ======");
        Iterator<String> iterator = ipSet.iterator();
        while (iterator.hasNext())
        {
          String ip = iterator.next();
          // broadcast token: [username,filename,poolid]
          byte[] byteMsg = (message + Constants.COMMA + id).getBytes();
          DatagramPacket datagramPacket;
          try
          {
            datagramPacket = new DatagramPacket(byteMsg, 
                                                byteMsg.length,
                                                InetAddress.getByName(ip), 
                                                Constants.CLIENT_UDP_PORT_INT);
            datagramSocket.send(datagramPacket);
            System.out.println("sending " + message + Constants.COMMA + id + " to " + ip + ":" + Constants.CLIENT_UDP_PORT);
          }
          catch (UnknownHostException e)
          {
            e.printStackTrace();
          }
          catch (IOException e)
          {
            e.printStackTrace();
          }
        }
        try
        {
          Thread.sleep(3000);
        }
        catch (Exception sleepException)
        {
          sleepException.printStackTrace();
        }
      }
      isPoolEnd = true;
    }
    catch (SocketException e)
    {
      e.printStackTrace();
    }

  }

}
